'use strict';

import Vue       from 'vue';
import VueRouter from 'vue-router';
import App       from './App.vue';
import routerMaps from './routers';
import { sync } from 'vuex-router-sync'
import store from './vuex/store'
import {getToken} from './vuex/getters'

Vue.use(VueRouter);

let router = new VueRouter({
    transitionOnLoad: false,
    hashbang           : true,
    history            : false,
    saveScrollPosition : true
});

routerMaps(router);

router.beforeEach((transition) => {
  const token = getToken(store.state.user);
  if (transition.to.auth) {
     if (token!=null) {
       transition.next();
     } else {
       const redirect = encodeURIComponent(transition.to.path);
       transition.redirect({ name: 'login', query: { redirect } });
     }
   } else {
     transition.next();
   }
});



let history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

/**
* sync router loading status
*/
const commit = store.commit || store.dispatch
router.beforeEach(({ to, from, next }) => {
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)
  if (toIndex) {
    if (toIndex > fromIndex) {
      commit('UPDATE_DIRECTION', 'forward')
    } else {
      commit('UPDATE_DIRECTION', 'reverse')
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    commit('UPDATE_DIRECTION', 'forward')
  }
  commit('UPDATE_LOADING', true)
  setTimeout(next, 50)
})
router.afterEach(() => {
  commit('UPDATE_LOADING', false)
})

sync(store, router)



router.start(Vue.extend(App), '#app');


router.redirect({
  '':'/home'
});
